package rpg.core
{
	import rpg.Utils.GameUtils;
	import rpg.animation.Animation;
	import rpg.animation.Frame;

	public class SceneAnimationComponent extends RenderComponent
	{
		private var animation : Animation;
		private var playDelay : int;
		private var runTimes : int;
		public var animationID : String;

		private var mapX : int;
		private var mapY : int;

		public function SceneAnimationComponent(type : * = null)
		{
			super(type == null ? SceneAnimationComponent : type);
		}

		public function setTargetXY(mapX : int , mapY : int) : void
		{
			this.mapX = mapX;
			this.mapY = mapY;
		}

		public function setAnimation(animation : Animation , zIndex : int , playDelay : int = 0 , loops : int = 0 , rotation : int = 0) : void
		{
			this.animation = animation;
			if(animation == null)
				return;
			this.playDelay = playDelay;
			animationID = animation.id;
			animation.loops = loops;
			render.zIndex = zIndex;
			render.rotate(rotation , animation.centerX , animation.centerY);
		}

		override public function update(delay : uint) : void
		{
			if(animation == null)
				return;
			runTimes += delay;
			if(runTimes > playDelay)
			{
				animation.tryNext(delay);
				updateRender(mapX - GameUtils.viewX , mapY - GameUtils.viewY , offsetX , offsetY);
			}
			if(animation.loops == 1 && animation.isEnd)
			{
				destroy();
			}
		}

		override public function updateRender(sceneX : int , sceneY : int , offsetX : int = 0 , offsetY : int = 0) : void
		{
			var frame : Frame = animation.curFrame;
			if(frame.data == null && frame.frameClass)
			{
				frame.data = new frame.frameClass(0 , 0);
			}
			render.bitmapData = frame.data;
			render.x = sceneX + frame.offsetX - offsetX;
			render.y = sceneY + frame.offsetY - offsetY;
		}

		override public function destroy() : void
		{
			super.destroy();
			animation = null;
		}

	}
}